/*
 * tim.c
 *
 *  Created on: 2025年3月29日
 *      Author: ceeu
 */
#include "tim.h"

/**
 * ftm 周期计算公式
 * 重装载值/（主频、分频） 单位秒
 *
 * eg. 1ms定时器
 * 1500（重装载值）/（48000000（主频）/32（分频系数）） = 1/1000 秒 = 1ms
 */

ftm_state_t     ftmStateStruct;
uint8_t         ftm0Flag = 0;
_TKS_FLAGA_type TKS_FLAGA;
_TKS_FLAGA_type bitFlag;

void ftmTimerISR(void) {
    static uint32_t count = 0;
    BIT_1MSF              = 1;
    count++;
    ftm0Flag = 1;
    if ((count % 10 == 0) && (count != 0)) {
        BIT_10MSF = 1;
    }
    if ((count % 50 == 1) && (count != 0)) {
        BIT_50MSF = 1;
    }
    if ((count % 100 == 2) && (count != 0)) {
        BIT_100MSF = 1;
    }
    if ((count % 500 == 3) && (count != 0)) {
        BIT_500MSF = 1;
    }

    FTM_DRV_ClearStatusFlags(INST_FLEXTIMER_MC1, FTM_TIME_OVER_FLOW_FLAG);
}
void timerFlagOpt(void) {
    TKS_1MSF   = BIT_1MSF;
    TKS_10MSF  = BIT_10MSF;
    TKS_50MSF  = BIT_50MSF;
    TKS_100MSF = BIT_100MSF;
    TKS_500MSF = BIT_500MSF;
    BIT_1MSF   = 0;
    BIT_10MSF  = 0;
    BIT_50MSF  = 0;
    BIT_100MSF = 0;
    BIT_500MSF = 0;
}

void timInit(void) {

    /* 初始化FTM模块 */
    FTM_DRV_Init(INST_FLEXTIMER_MC1, &flexTimer_mc1_InitConfig, &ftmStateStruct);
    /* 配置并使定时器能溢出中断 */
    INT_SYS_InstallHandler(FTM0_Ovf_Reload_IRQn, &ftmTimerISR, (isr_t *)0U);
    INT_SYS_EnableIRQ(FTM0_Ovf_Reload_IRQn);
    /* 初始化计数器 */
    FTM_DRV_InitCounter(INST_FLEXTIMER_MC1, &flexTimer_mc1_TimerConfig);
    FTM_DRV_CounterStart(INST_FLEXTIMER_MC1);
}
